<template>
  <div class="echo-page">
    <div class="none-container">
      <div class="form-item">
        <el-cascader
          size="medium"
          :clearable="true"
          collapse-tags
          :ref="`CascaderApplicableArea`"
          :options="shopLocationOptions"
          v-model="myForm.applicableArea"
          :props="shopLocationProps"
          @change="handleShopLocationChange"
        >
        </el-cascader>

        <el-cascader
          size="medium"
          filterable
          :clearable="true"
          :collapse-tags="!isReadonly"
          :ref="`ShopTree`"
          :options="shopTreeOptions"
          v-model="myForm.applicableShop"
          :props="shopTreeProps"
          @change="handleShopTreeChange"
        >
        </el-cascader>
      </div>
    </div>
    <div class="echo-form">
      <el-form
        ref="myForm"
        :model="myForm"
        :rules="formRules"
        label-width="100px"
      >
        <div class="line-title">
          <div class="line"></div>
          <div class="title">门店基础信息</div>
        </div>

        <div class="line-body">
          <el-row>
            <el-col :span="8">
              <el-form-item label="门店名称:">
                {{ shopBasicInfo.shopAppName || shopBasicInfo.shopName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门店类型:">
                {{ $t("outlet.shopType" + shopBasicInfo.shopType) }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门店类别:">
                {{
                  [
                    "",
                    $t("outlet.showingType0"),
                    $t("outlet.showingType1"),
                    $t("outlet.showingType2"),
                  ][shopBasicInfo.shopShowingType]
                }}
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="!isPlatform">
            <el-col :span="8">
              <el-form-item label="申请时间:">
                {{ myForm.activityCheckTime }}
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="line-line"></div>
        <div class="line-title">
          <div class="line"></div>
          <div class="title">{{ acTypeInfo.activityTypeName }}</div>
        </div>

        <div class="line-body">
          <el-row>
            <el-col :span="8">
              <el-form-item label="活动名称:">
                {{ myForm.activityName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="活动类型:">
                {{ ["", "平台活动", "商户活动"][myForm.marketId] }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label-width="140px" label="与其他活动关系:">
                {{
                  ["", "与其他活动互斥，不能同时享受", "可叠加享受"][
                    myForm.activityRelationshipState
                  ]
                }}
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="宣传图片:">
                <DirectImgUpload
                  :disabled="true"
                  :modelValue.sync="myForm.activityImg"
                  :limit="1"
                  width="750px"
                  height="600px"
                  cropW="750"
                  cropH="600"
                  :prompt="false"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="使用对象:">
                {{ ["", "旅客", "员工"][myForm.activityUseState] }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label-width="140px" label="备注:">
                {{ myForm.activityMsg }}
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="line-line"></div>
        <div v-if="!isPlatform">
          <div class="line-title">
            <div class="line"></div>
            <div class="title">适用商品范围标签</div>
          </div>

          <div class="line-body">
            <el-row>
              <el-col
                :span="12"
                v-for="item in myForm.applicableAreaShopCategory"
                :key="item.categoryId"
              >
                <div class="category-title">
                  <img
                    class="category-mini-icon"
                    src="@/assets/icon/category-mini-icon.png"
                    alt=""
                  />
                  {{ item.categoryName }}
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div v-if="isPlatform">
          <div class="line-title">
            <div class="line"></div>
            <div class="title">适用区域</div>
          </div>

          <div class="line-body">
            <el-row>
              <el-col
                :span="6"
                v-for="(item, index) in applicableAreaArr"
                :key="index"
              >
                <div class="category-title">
                  <img
                    class="category-mini-icon"
                    src="@/assets/icon/category-mini-icon.png"
                    alt=""
                  />
                  {{ item }}
                </div>
              </el-col>
            </el-row>
          </div>

          <div class="line-title">
            <div class="line"></div>
            <div class="title">适用商户</div>
          </div>

          <div class="line-body">
            <el-row>
              <el-col
                :span="12"
                v-for="(item, index) in applicableShopArr"
                :key="index"
              >
                <div class="category-title">
                  <img
                    class="category-mini-icon"
                    src="@/assets/icon/category-mini-icon.png"
                    alt=""
                  />
                  {{ item }}
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="line-line"></div>
        <div class="line-title">
          <div class="line"></div>
          <div class="title">活动时间</div>
        </div>
        <div class="line-body">
          <div class="time-radio">
            <span class="active-time-label">活动时间: </span
            >{{ mapViewActiveTime(myForm) }}
          </div>
        </div>
        <div class="line-line"></div>
        <div class="line-title">
          <div class="line"></div>
          <div class="title">{{ acTypeInfo.activityTypeName }}</div>
        </div>
        <ReadonlyActiveType
          v-if="acTypeInfo.id"
          :acTypeInfo="acTypeInfo"
          :isPlatform="isPlatform"
          :categoryProductVos="categoryProductVos"
          :activityMerchantProdList="activityMerchantProdList"
          ref="ReadonlyActiveTypeComponent"
        ></ReadonlyActiveType>
      </el-form>
    </div>
    <div class="footer" v-if="!isReadonly">
      <div class="footer-box">
        <el-button
          class="button"
          type="succenss"
          size="small"
          @click="$router.back()"
          >返回</el-button
        >
        <div>
          <el-button
            class="button"
            type="primary"
            size="small"
            @click="pass(true)"
            >审核</el-button
          >
          <!-- <el-button
            class="button"
            type="danger"
            size="small"
            @click="pass(false)"
            >驳回</el-button
          > -->
        </div>
      </div>
    </div>
    <AuditDialog ref="AuditDialog" />
  </div>
</template>

<script>
import { _types, _weeks, _days } from "./promotionMethodComps/definition";
import ReadonlyActiveType from "./promotionMethodComps/ReadonlyActiveType";
import AuditDialog from "./AuditDialog.vue";
export default {
  components: {
    ReadonlyActiveType,
    AuditDialog,
  },
  data() {
    return {
      acTypeInfo: {},
      id: "",
      action: "add",
      shopBasicInfo: {},
      useTypes: _types,
      useWeeks: _weeks,
      useDays: _days,
      timer: [],
      timePickerValueByDay: null,
      timePickerValueByWeek: null,
      timePickerValueByMonth: null,
      myForm: {
        marketId: 1,
        activityTimeState: 2,
        applicableArea: [],
      },
      checkboxGroups: [],
      formRules: {
        activityName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        marketId: [
          { required: true, message: "请选择活动类型", trigger: "change" },
        ],
        activityImg: [
          {
            required: true,
            message: "请上传活动图片",
            trigger: "change",
          },
        ],
        applicableArea: [
          { required: true, message: "请选择适用区域", trigger: "change" },
        ],
        applicableShop: [
          { required: true, message: "请选择适用门店", trigger: "change" },
        ],
        activityTimeState: [
          {
            required: true,
            message: "请选择活动时间",
            trigger: ["change", "blur"],
          },
        ],
        activityRelationshipState: [
          {
            required: true,
            message: "请选择与其他活动关系",
            trigger: ["change", "blur"],
          },
        ],
        activityUseState: [
          {
            required: true,
            message: "请选择使用对象",
            trigger: ["change", "blur"],
          },
        ],
      },
      shopLocationOptions: [],
      shopLocationProps: {
        label: "name",
        value: "id",
        multiple: true,
      },
      shopTreeProps: {
        label: "name",
        value: "id",
        children: "childList",
        multiple: true,
      },
      shopTreeOptions: [],

      categoryProductTree: [],
      categoryProductProps: {
        label: "name",
        value: "id",
        // children:"productList",
        multiple: true,
      },
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      categoryProductVos: [],
      activityMerchantProdList: [],

      applicableAreaArr: [],
      applicableShopArr: [],
    };
  },
  computed: {
    // 查看
    isReadonly() {
      return this.action === "readonly";
    },
    // 审批
    isAudit() {
      return this.action === "audit";
    },
    isPlatform() {
      return this.myForm.activityBusinessState == 1;
    },
  },
  created() {
    // 区域树
    this.queryShopLocation();
    let { acTypeInfo, id, action } = this.$route.query;
    if (acTypeInfo) {
      this.acTypeInfo = JSON.parse(acTypeInfo);
      this.myForm.activityMarketTypeId = this.acTypeInfo.id;
      this.myForm.activityMarketTypeName = this.acTypeInfo.activityTypeName;
    }
    if (id) {
      this.id = id;
      this.action = action;
      if (this.isReadonly) {
        this.$store.commit("common/replaceSelectMenu", "查看活动");
      }
    }
  },
  mounted() {
    if (this.id) {
      this.getActiveInfo();
    }
  },
  methods: {
    mapViewActiveTime(row) {
      function mapWeekDay(str) {
        if (!str) return "";
        let weekTexts = [
          "",
          "周一",
          "周二",
          "周三",
          "周四",
          "周五",
          "周六",
          "周日",
        ];
        return str
          .split(",")
          .sort()
          .map((m) => ` ${weekTexts[m]} `);
      }
      if (row.activityTimeState == 1) {
        if (row.activityTimeCycleState == 0) {
          return `每天 ${row.activityCycleStartTime}~${row.activityCycleEndTime}`;
        }
        if (row.activityTimeCycleState == 1) {
          return `每周 ${mapWeekDay(row.weekDays)} ${
            row.activityCycleStartTime
          }~${row.activityCycleEndTime}`;
        }
        if (row.activityTimeCycleState == 2) {
          return `每月${row.activityTimeNum}号 ${row.activityCycleStartTime}~${row.activityCycleEndTime}`;
        }
      }
      return `${row.activityStartTime} ~ ${row.activityEndTime}`;
    },
    getActiveInfo() {
      this.$http({
        url: this.$http.adornUrl(`/platform/activity/${this.id}`),
        method: "get",
      }).then(async ({ data }) => {
        let acTypeInfo = _types.find(
          (m) => m.id == data.activity.activityMarketTypeId
        );
        this.acTypeInfo = acTypeInfo;
        this.getShopInfo(data.activityMerchantList[0].merchantId);
        if (data.activity.activityTimeState == 2) {
          // 如果选择的是时间 ，需拼接日期
          this.timer = [
            `${data.activity.activityStartTime}`,
            `${data.activity.activityEndTime}`,
          ];
        } else {
          // 如果选择的是周期
          let t = [
            data.activity.activityCycleStartTime,
            data.activity.activityCycleEndTime,
          ];
          if (data.activity.activityTimeCycleState == 0) {
            // 天
            this.timePickerValueByDay = t;
          } else if (data.activity.activityTimeCycleState == 1) {
            // 周
            this.timePickerValueByWeek = t;
            this.checkboxGroups = [];
          } else if (data.activity.activityTimeCycleState == 2) {
            // 月
            this.timePickerValueByMonth = t;
            // activityTimeNum
          }
        }
        // 适用区域
        if (data.activity.applicableArea) {
          data.activity.applicableArea = JSON.parse(
            data.activity.applicableArea
          );
          if (data.activity.activityBusinessState == 1) {
            data.activity.applicableArea = data.activity.applicableArea.map(
              (m) => m.airportShopAddressIds
            );
            this.myForm.applicableArea = data.activity.applicableArea;
            this.handleShopLocationChange();
          } else {
            data.activity.applicableArea = data.activity.applicableArea.map(
              (m) => m.prodCategoryIds
            );
            this.myForm.applicableArea = data.activity.applicableArea;
            this.searchProdsByCurrentShop(
              data.activityMerchantList[0].merchantId,
              data.activity.activityShopDeliveryStatus
            );
          }
        }
        // 适用商户
        if (data.activity.applicableShop) {
          data.activity.applicableShop = JSON.parse(
            data.activity.applicableShop
          );
          data.activity.applicableShop = data.activity.applicableShop.map(
            (m) => m.shopIds
          );
          this.myForm.applicableShop = data.activity.applicableShop;
          await this.getConformShopList();
          this.handleShopTreeChange();
        }
        this.myForm = data.activity;
        this.categoryProductVos = data.categoryProductVos;
        this.activityMerchantProdList = data.activityMerchantProdList;
      });
    },
    // 根据商户查询商品
    searchProdsByCurrentShop(shopId, dvyType) {
      this.$http({
        url: this.$http.adornUrl("/prod/prod/gatCategoryProduct"),
        method: "get",
        params: this.$http.adornParams({ shopId, dvyType }),
      }).then(({ data }) => {
        if (data) {
          console.log(this.myForm.applicableArea);
          // 数组扁平化
          let applicableAreaShopCategoryIds = this.myForm.applicableArea.map(
            (m) => m[0]
          );
          this.categoryProductTree = data;
          let applicableAreaShopCategory = data.filter((f) =>
            applicableAreaShopCategoryIds.includes(f.categoryId)
          );
          this.$set(
            this.myForm,
            "applicableAreaShopCategory",
            applicableAreaShopCategory
          );
        }
      });
    },

    // 获取区域
    queryShopLocation() {
      this.$http({
        url: this.$http.adornUrl("/admin/platform/airportStation/list"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.shopLocationOptions = data;
      });
    },
    // 适用区域
    handleShopLocationChange() {
      this.$nextTick(() => {
        let nodes = this.$refs.CascaderApplicableArea.getCheckedNodes(true);
        console.log(nodes, nodes.length);
        let applicableAreaArr = [];
        if (nodes.length) {
          applicableAreaArr = nodes.map((m) => m.pathLabels.join("-"));
        }
        this.applicableAreaArr = applicableAreaArr;
      });
    },
    // 适用商户
    handleShopTreeChange() {
      let nodes = this.$refs.ShopTree.getCheckedNodes(true);
      let applicableShopArr = [];
      if (nodes.length) {
        applicableShopArr = nodes.map((m) => m.pathLabels.at(-1));
      }
      this.applicableShopArr = applicableShopArr;
    },
    // 适用商户
    getConformShopList() {
      return new Promise((resolve, reject) => {
        if (
          this.myForm.applicableArea &&
          this.myForm.applicableArea.length > 0
        ) {
          let addressId = this.myForm.applicableArea.map((m) => {
            return m[m.length - 1];
          });
          this.$http({
            url: this.$http.adornUrl(
              "/platform/shopDetail/getAddressIdShopList"
            ),
            method: "post",
            data: addressId,
          })
            .then(({ data }) => {
              this.shopTreeOptions = data;
              resolve();
            })
            .catch(reject);
        }
      });
    },
    getShopInfo(shopId) {
      this.$http({
        url: this.$http.adornUrl("/platform/shop/info/" + shopId),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.shopBasicInfo = data.shopDetail;
      });
    },
    pass() {
      this.$refs.AuditDialog.init({
        id: this.id,
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.flex {
  display: flex;
}

.warp {
  flex-wrap: wrap;
}

.echo-page {
  ::v-deep .el-form-item {
    margin-bottom: 0 !important;
  }
}

.echo-form {
  padding-bottom: 100px;
}

.line-title {
  margin-bottom: 24px;
}

.line-line {
  width: 100%;
  height: 1px;
  background: #f5f5f5;
  border-radius: 2px;
  margin-bottom: 24px;
}
.time-radio {
  margin-left: 10px;
  margin-bottom: 20px;
}
.active-time-label {
  margin-right: 10px;
}

.footer {
  z-index: 8;
  position: fixed;
  width: calc(100% - 250px);
  bottom: 0;
  padding: 10px;
  padding-left: 20px;
  padding-right: 20px;
  box-shadow: 4px 2px 5px 5px #eee;
  background: #fff;
  margin-left: -20px;

  .footer-box {
    display: flex;
    flex-direction: row-reverse;
    justify-content: space-between;

    .button {
      margin-right: 20px;
    }
  }
}

.category-title {
  width: 95%;
  height: 36px;
  background: #f8f8f8;
  border-radius: 4px;
  margin-bottom: 12px;
  line-height: 36px;
  box-sizing: border-box;
  padding-left: 14px;
  display: flex;
  align-items: center;
  .category-mini-icon {
    height: 16px;
    width: 16px;
    margin-right: 10px;
    transform: translateY(-5%);
  }
}
.none-container {
  display: none;
}
</style>
